<!-- 新增表单区域 -->
<template>
  <a-modal v-model:open="openModel" width="1000px" title="新增排课申请" @ok="onFinish()" ok-text="提交"
           cancel-text="取消">
    <a-form
        :model="formState"
        v-bind="layout"
        name="nest-messages"
        :validate-messages="validateMessages"
    >
      <a-form-item v-for="{key,title,inputType,rules,selectList} in formFields" :key="key" :name="[key]" :label="title"
                   :rules="rules">
        <template v-if="inputType === 'input'">
          <a-input v-model:value="formState[key]"/>
        </template>
        <template v-else-if="inputType === 'input-number'">
          <a-input-number v-model:value="formState[key]"/>
        </template>
        <template v-else-if="inputType === 'textarea'">
          <a-textarea v-model:value="formState[key]"/>
        </template>
        <template v-else-if="inputType === 'date'">
          <a-date-picker v-model:value="formState[key]"/>
        </template>
        <template v-else-if="inputType === 'select'">
          <a-select
              placeholder="请选择"
              v-model:value="formState[key]"
              style="width: 200px"
          >
            <a-select-option v-for="{selectKey,selectName} in selectList"
                             :value="selectKey"
                             :key="selectKey">
              {{ selectName }}
            </a-select-option>
          </a-select>
        </template>

        <!--        学期定制化组件-->
        <template v-else-if="inputType === 'semester-input'">
          <a-form-item style="margin-bottom: -20px">
            <a-range-picker
                :disabled-date="disabledDate"
                v-model:value="formState[key+'_year']"
                picker="year"
                @calendarChange="onCalendarChange"
            />
            -
            <a-select
                placeholder="请选择学期"
                v-model:value="formState[key+'_semester']"
                style="width: 200px"
                :options="[{ label: '1', value: '1' }, { label: '2', value: '2' }]"
            ></a-select>
          </a-form-item>
        </template>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">

//新增的表单数据
import {onMounted, reactive, ref} from "vue";
import {Dayjs} from 'dayjs';
import {$addExperiment} from '@/views/experimentApplication/add/experimentAdd.api'
import {$getLabTypeList, $getSectionList, $getSemesterList, $getWeekdayList} from "@/api/loadDictList";
import {message} from "ant-design-vue";


onMounted(async () => {
  let semesterList = await $getSemesterList();
  let labTypeList = await $getLabTypeList();
  let sectionList = await $getSectionList();
  let weekdayList = await $getWeekdayList();

  formFields.value.forEach((fieldItem: any) => {
    if (fieldItem.key == "semesterId") {
      fieldItem.selectList.length=0
      //将后端获取的semesterList放入formFields
      semesterList.forEach((semesterItem: any) => {
        const {id: selectKey, semesterName: selectName} = semesterItem
        const newSemesterItem = {selectKey: selectKey, selectName: selectName}
        fieldItem.selectList.push(newSemesterItem)
      })
    }
    if (fieldItem.key == "labType") {
      fieldItem.selectList.length=0
      //将后端获取的semesterList放入formFields
      labTypeList.forEach((labTypeItem: any) => {
        const {id: selectKey, labTypeName: selectName} = labTypeItem
        const newSemesterItem = {selectKey: selectKey, selectName: selectName}
        fieldItem.selectList.push(newSemesterItem)
      })
    }
    if (fieldItem.key == "section") {
      fieldItem.selectList.length=0
      //将后端获取的semesterList放入formFields
      sectionList.forEach((sectionItem: any) => {
        const {id: selectKey, sectionName: selectName} = sectionItem
        const newSemesterItem = {selectKey: selectKey, selectName: selectName}
        fieldItem.selectList.push(newSemesterItem)
      })
    }
    if (fieldItem.key == "weekday") {
      fieldItem.selectList.length=0
      //将后端获取的semesterList放入formFields
      weekdayList.forEach((weekdayItem: any) => {
        const {id: selectKey, weekdayName: selectName} = weekdayItem
        const newSemesterItem = {selectKey: selectKey, selectName: selectName}
        fieldItem.selectList.push(newSemesterItem)
      })
    }
  })
  return formFields;

})
const formState = reactive({
  labType: undefined
});

const layout = {
  labelCol: {span: 3},
  wrapperCol: {span: 16},
};
//控制开关Model
const openModel = defineModel('openModel')
//控制里面的表单
const formFields = defineModel('formFields')
//成功后刷新
const emit = defineEmits(['submitSuccess'])
//定义的规则
const validateMessages = {
  required: '${label}不能为空',
  types: {
    email: '${label}不是一个有效的邮箱格式',
  },
  number: {
    range: '${label} 必须在${min}和${max}之间',
  }
};

//新增数据
const onFinish = async () => {

  console.log("formState",  formState);
  const {classname,courseName,endWeek,labType,section,semesterId,startWeek,studentCount,weekday} = formState
  if(semesterId==null){
    message.error("学期不能为空")
    return
  }
  if(courseName==null){
    message.error("课程名称不能为空")
    return
  }
  if(labType==null){
    message.error("实验室类型不能为空")
    return
  }
  if(classname==null){
    message.error("班级不能为空")
    return
  }
  if(studentCount==null){
    message.error("学生人数不能为空")
    return
  }
  if(startWeek==null){
    message.error("起始周不能为空")
    return
  }
  if(endWeek==null){
    message.error("结束周不能为空")
    return
  }
  if(section==null){
    message.error("节次不能为空")
    return
  }
  if(weekday==null){
    message.error("上课时间不能为空")
    return
  }

  try{
    let result = await $addExperiment(formState);
    if(result.code==200){
      console.log("result22",result);
      message.success(result.data)
      openModel.value=false;
      emit('submitSuccess');

    }else{
      message.error(result.message)
    }
  }catch(e){
    message.error(e.message)
  }
}

/*
日期限制在一学年
 */
type RangeValue = [Dayjs, Dayjs];
const dates = ref<RangeValue>();
const disabledDate = (current: Dayjs) => {
  if (!dates.value || (dates.value as any).length === 0) {
    return false;
  }
  const tooLate = dates.value[0] && current.diff(dates.value[0], 'years');
  const tooEarly = dates.value[1] && dates.value[1].diff(current, 'years');
  return tooEarly || tooLate;
};
const onCalendarChange = (val: RangeValue) => {
  dates.value = val;
};
</script>